<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>注册</title>
  <script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
  <script src="__PUBLIC__/script/common.js" common-data-1="{:U('Mix/dest')}"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/jquery-weui.min.js"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/city-picker.min.js"></script>
  <!-- <script src="__PUBLIC__/script/mockjs/dist/mock-min.js"></script> -->
  <!-- <script src="__PUBLIC__/script/pub/fake.js"></script> -->
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/lib/weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/css/jquery-weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/base.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/signup.css">
  <style>
    pre{display:none;}
  </style>
</head>
<body>
  <div style='display:none;' id='displayNone'>
    <input type="hidden" name="获取短信验证码" id='url_getCode' value="{:U('Home/index/sms')}" form='not_submit'>
    <input type="hidden" name="获取渠道列表" id='getQudaoURL' value="{:U('Wchat/get_qudao_list')}">
    <input type="hidden" name="验证手机是否重复" id='re_ck_phone' value="{:U('Home/index/re_ck_phone')}">
  </div>
  <div class="container">
    <div class="logo" style="width:70%;min-width:200px;margin:auto;">
      <img src="__PUBLIC__/res/logo.png" alt="logo" style='width:100%;'>
    </div>
    <div style='display:none;'>
    </div>
    <div class="signup">
      <form autocomplete="off" action="{:U('Wchat/signup')}" method="post" id = 'signUp'>
        <!-- <div class="weui-cell local">
          <div class="time_line">
            <span class="round_number">1</span>
          </div>
          <div class="weui-cell__hd">
              <label for="city-picker" class="weui-label">选择申贷地点</label>
          </div>
          <div class="weui-cell__bd">
              <input form="gen_form" name = 'daikuan_local' type="text" id='city-picker' class="weui-input" placeholder="请选择地址"/>
          </div>
        </div> -->
        <if condition="$message['q'] eq 'yh'">
        <input type="text" name="city_picker" id="city_picker" form='not_sunmit' readonly placeholder="请选择注册地点"><br>
        <input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly placeholder="请先选择城市">
        </if>
        <div class="tel_box">
          <input type="tel" autocomplete="off" name="web_phone" id="web_phone" placeholder="手机号码"><button id='getCode'>获取验证码</button>
        </div>
        <input type="text" name="web_yanzheng_code" id="signup_yanzheng_code" placeholder="输入验证码"><br>
        <input type="text" name="web_name" id="signup_nick_name" placeholder="输入昵称"><br>
        <input type="password" autocomplete="off" name="web_pass" id="signup_yaoqin" placeholder="密码"><br>
        <if condition='$message neq null' >
        <input class="checkDone" type="text" name="code" value="{$message.code}" style="display: none;">
        <input type="text" name="type" value="{$message.type}" style="display: none;">
        <else/>
        <!-- 推荐码按照给予方法加密传输解密值 -->
        <input type="text" name="code" value="" placeholder="推荐码" id='invent_code' required>
        <input type="text" name="type" value="5" style="display: none;" required>
        </if>
        <input type="text" name="ToUserName" value="{$message.ToUserName}" style="display: none;">
        <input type="submit" id = "sign_submit" value="完成注册">
      </form>
    </div>
    <div class="more flex">
      <div class="float_left"><a href="{:U('Wchat/huoquyaoqin')}">如何获得邀请码？</a></div>
      <div class="float_right"><a href="{:U('Wchat/huoquyaoqin')}?front_end='qiye'">企业注册</a></div>
      <div class="float_clear"></div>
    </div>
  </div>
  <div class="bottomMess"><span><a href="{:U('Wchat/login')}">返回登陆</a></span></div>
  <script id='city_picker_script'>
    $(document).ready(() => {
      // 储存公众号id
      const wechatIndex = `{$this_wechat_id}`
      if (wechatIndex && Number.isInteger(Number.parseInt(wechatIndex))) {
        localStorage.clear()
        localStorage.setItem('login_index', `${wechatIndex}`)
        localStorage.setItem('login', `http://pgl.oaio.online/index.php/web/wchat/login/wechat_id/${wechatIndex}`)
      }
      $("#city_picker").cityPicker({
        title: "请选择注册地点",
        onClose: () => {
          const resignCode = $("#city_picker").attr('data-codes').split(',')
          const ajaxURL = String($(`#getQudaoURL`).val())
          const ajaxData = {
            qudao_pro_id: resignCode[0],
            qudao_city_id: resignCode[1],
            qudao_area_id: resignCode[2]
          }
          const listArray = {}
          listArray.title = '请选择城市'
          listArray.cols = [{
            textAlign: 'center',
            values: [],
            displayValues: []
          }]
          listArray.onChange = (picker, values, displayValues) => {
            $("#qudao_picker").attr('inori-data-code', values[0])
            setTimeout(()=>{$("#qudao_picker").val(displayValues[0])}, 0)
            // $("#qudao_picker").val(null)
            // const tempTempl = `<input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly>`
            // $('#qudao_picker').remove()
            // $('.tel_box').before(tempTempl)
          }
          $("#qudao_picker").val(null)
          const tempTempl = `<input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly>`
          $('#qudao_picker').remove()
          $('.tel_box').before(tempTempl)
          $.ajax(ajaxURL, {
            method: 'post',
            data: ajaxData
          }).fail((err) => {
            $("#qudao_picker").off('click')
            $("#qudao_picker").on('click', (evt) => {
              evt.preventDefault()
              $.toptip(`请先选择城市等待网络加载成功提示`, 'wraning')
            })
            $.toptip(`网络通信失败`, 'error')
            listArray.cols[0].values.push(`null`)
            listArray.cols[0].displayValues.push(`请检查网络`)
            const tempTempl = `<input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly>`
            $('#qudao_picker').remove()
            $('.tel_box').before(tempTempl)
            $('#qudao_picker').picker(listArray)
            throw err
          }).done((res) => {
            $.toptip('渠道列表获取成功', 'success')
            if (res.code && String(res.code) === '1') {
              $("#qudao_picker").off('click')
              const resData = res.data
              $.each(resData, (index, item) => {
                listArray.cols[0].values.push(`${item.qudao_id}`)
                listArray.cols[0].displayValues.push(`${item.qudao_name}`)
              })
              const tempTempl = `<input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly>`
              $('#qudao_picker').remove()
              $('.tel_box').before(tempTempl)
              $('#qudao_picker').picker(listArray)
            } else {
              $("#qudao_picker").off('click')
              $("#qudao_picker").on('click', (evt) => {
                evt.preventDefault()
                $.toptip(`请选择其他城市等待网络加载成功提示`, 'wraning')
              })
              listArray.cols[0].values.push(`null`)
              listArray.cols[0].displayValues.push(`请选择其他城市`)
              $.toptip(`渠道列表获取失败：${res.message}`, 'error')
              const tempTempl = `<input type="text" name="qudao_picker" id="qudao_picker" form='not_sunmit' readonly>`
              $('#qudao_picker').remove()
              $('.tel_box').before(tempTempl)
              // $('#qudao_picker').picker(listArray)
            }
          })
        }
      })
      // $("#qudao_picker").picker({
      //   title: "请选择您的城市",
      //   cols: [
      //     {
      //       textAlign: 'center',
      //       values: [
      //         'null',
      //       ],
      //       displayValues: [
      //         '请选择城市',
      //       ]
      //     }
      //   ],
      //   onChange: (picker, values, displayValues) => {
      //     $("#qudao_picker").attr('inori-data-code', values[0])
      //     setTimeout(()=>{$("#qudao_picker").val(displayValues[0])}, 0)
      //   }
      // })
      $("#qudao_picker").on('click', (evt) => {
        evt.preventDefault()
        $.toptip(`请先选择城市等待网络加载成功提示`, 'wraning')
      })
    })
  </script>
  <script>
    let code = '{$message.code}'
    let type = '{$message.type}'
    // 推荐人
    let php_u = '{$message.u}'
    // 渠道，当q = ajy 的时候是按揭员
    let php_q = '{$message.q}'
    let ToUserName = '{$message.ToUserName}'
    var phone = $('#signup_phone').val()
    $('#sign_submit').on('click', function post (evt) {
      // 转换邀请码
      // 特殊处理
      if (!$(`input[name='code']`).hasClass('checkDone')) {
        $.toptip('请填写有效推荐码')
        evt.preventDefault()
        throw new Error('请填写有效推荐码')
      }
      if ($('#invent_code').length > 0) {
        const realcode = Number($('#invent_code').val().replace(/\D/g,'')) - 5000
        if (realcode < 0 ) {
          $.toptip('请填写有效推荐码')
          evt.preventDefault()
          throw new Error('请填写有效推荐码')
        }
        // 这里不做处理
        // $('#invent_code').val(realcode)
      }

      // 判断密码
      if($('#signup_yaoqin').val() === '' || $('#signup_yaoqin').val().length < 8) {
        $.toptip('请填写8位以上密码！', 'error')
        evt.preventDefault()
        throw new Error(`请填写8位以上密码！`)
      }
      // 判断昵称
      if($('#signup_nick_name').val() === '') {
        $.toptip('请填写完整注册信息！', 'error')
        evt.preventDefault()
        throw new Error(`请填写完整注册信息！`)
      }
      // 判断邀请码是否有效
      // if($(`input[name='code']`).val() !== '') {
      //   const ajaxURL = ``
      //   let chackCode = 0
      //   if ($(`input[name='code']`).attr('id') === 'invent_code') {
      //     chackCode = $(`input[name='code']`).val() - 5000
      //   } else {
      //     chackCode = $(`input[name='code']`).val()
      //   }
      //   const ajaxData = {
      //     web_code: chackCode
      //   }
      // } else {
      //   $.toptip('请填写完整推荐信息！', 'error')
      //   throw new Error(`请填写完整推荐信息！`)
      // }
      // $.get(`./test?value=${phone}`, function(data){console.dir(data) })
      let url = `${$('#signUp').attr('action')}?code+${code}&type=${type}&ToUserName=${ToUserName}`
      if (php_u !== ``) {
        url += `&u=${php_u}`
        $(`#temp_php_u`).remove()
        $('#signUp').append(`<input type='hidden' name='u' value='${php_u}' id='temp_php_u'>`)
      }
      if (php_q !== `yh`) {
        url += `&q=${php_q}`
        $(`#temp_php_q`).remove()
        $('#signUp').append(`<input type='hidden' name='q' value='${php_q}' id='temp_php_q'>`)
      } else {
        $(`#temp_php_q`).remove()
        const qudaoValue = $(`#qudao_picker`).attr(`inori-data-code`)
        if (qudaoValue === 'null' || qudaoValue === undefined || qudaoValue === '') {
          $.toptip(`渠道选择错误，请检查`, 'error')
          event.preventDefault()
          throw new Error(`渠道选择错误`)
        }
        $('#signUp').append(`<input type='hidden' name='q' value='${qudaoValue}' id='temp_php_q'>`)
      }
      // 判断验证码是否填写正确
      const yanzheng_code = sessionStorage.getItem(`yanzheng_code`)
      if (yanzheng_code === null || yanzheng_code !== `${String($('#signup_yanzheng_code').val())}`) {
        $.toptip(`验证码填写错误，请检查`, 'error')
        event.preventDefault()
        throw new Error(`验证码填写错误`)
      }
      // 转换val为id
      let cityValue = {}
      if ($(`#city_picker`).attr(`data-codes`)) {
        cityValue = $(`#city_picker`).attr(`data-codes`).split(',')
        /*
          $user['web_pro_id']=$_POST['u_pro_id'];
			    $user['web_city_id']=$_POST['u_city_id'];
			    $user['web_area_id']=$_POST['u_area_id'];
        */
        if (cityValue[0]) {
          $(`#temp_value_u_pro_id`).remove()
          $('#signUp').append(`<input type='hidden' name='u_pro_id' value='${cityValue[0]}' id='temp_value_u_pro_id'>`)
        }
        if (cityValue[1]) {
          $(`#temp_value_u_city_id`).remove()
          $('#signUp').append(`<input type='hidden' name='u_city_id' value='${cityValue[1]}' id='temp_value_u_city_id'>`)
        }
        if (cityValue[2]) {
          $(`#temp_value_u_area_id`).remove()
          $('#signUp').append(`<input type='hidden' name='u_area_id' value='${cityValue[2]}' id='temp_value_u_area_id'>`)
        }
      }
      if ($('#invent_code').length > 0) {
        const realcode = Number($('#invent_code').val().replace(/\D/g,'')) - 5000
        if (realcode < 0 ) {
          $.toptip('请填写有效推荐码')
          evt.preventDefault()
          throw new Error('请填写有效推荐码')
        }
        $('#invent_code').val(realcode)
      }
      $('#signUp').attr('action', url).submit()
    })
  </script>
  <script>
    $(document).ready(() => {
      if($('#PHPerrorMsg').length > 0) {
        let ErrorMsg = $('#PHPerrorMsg').text()
        $('#sign_submit').off('click')
        $('#sign_submit').css('background-color', '#ccc')
        $('#getCode').css({backgroundColor:'#ccc', color: '#fff'})
        $.toast(ErrorMsg, 'forbidden')
        $('#getCode').on('click', (evt) => {
          evt.preventDefault()
          $.toast(ErrorMsg, 'forbidden')
        })
        $('#sign_submit').on('click', (evt) => {
          evt.preventDefault()
          $.toast(ErrorMsg, 'forbidden')
        })
      } else {
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
      }
    })
  </script>

  <!-- 验证码相关，包括倒数，gen随机密码，发送密码 -->
  <script>
    function changeCountDownNum (id, num, fn, placeholder) {
      if (num >= 0) {
        $(`#${id}`).text(num--)
        return setTimeout(fn, 1000, id, num, changeCountDownNum, placeholder)
      } else {
        $(`#${id}`).text(placeholder)
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        return null
      }
    }
    // gen一个随机数值串出来
    function genRandCode (leng) {
      if( String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
      else {
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
      }
    }
    function sendCode (evt) {
      evt.preventDefault()

      // 正则，暂时没用上
      const isChinaMobile = /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/; //移动方面最新答复
      const isChinaUnion = /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/; //向联通微博确认并未回复
      const isChinaTelcom = /^(?:133|153|177|18[019])\d{8}$/; //1349号段 电信方面没给出答复，视作不存在
      const isOtherTelphone  = /^170([059])\d{7}$/;//其他运营商

      const phoneValue = $(`#${evt.data.phoneID}`).val().replace(/\s/g,'')
      const send_code = genRandCode(8)
      if (phoneValue.length !== 11) {
        $.toptip('请输入有效中国大陆手机号', 'error')
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        throw new Error(`手机号码判断为误：${phoneValue}`)
      } else {
        // 验证手机号码是否重复
        const checkURL = String($('#re_ck_phone').val())
        const ajaxData = {
          phone: phoneValue
        }
        $.ajax(checkURL, {
          method: 'post',
          data: ajaxData,
          async: false
        }).fail((err) => {
          event.preventDefault()
          $.toptip('检查手机号时网络通信失败','error')
          $('#getCode').off('click')
          $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
          throw err
        }).done((res) => {
          if (res.code && String(res.code) === '1') {
            $.toptip('手机号可用，正在发送验证码','success')
          } else if (res.code && String(res.code) === '2') {
            event.preventDefault()
            $.toptip('手机号已被注册','warning')
            $('#getCode').off('click')
            $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
            throw new Error(`手机号已被注册`)
          } else {
            event.preventDefault()
            $.toptip('未知返回, 查看控制台得到更多消息','error')
            console.log(`验证手机时服务器返回：${res}`)
            $('#getCode').off('click')
            $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
            throw new Error(`验证手机时服务器返回错误`)
          }
        })
      }
      const smsURL = $(`#${evt.data.urlID}`).val()
      let timer = ''
      $(`#${evt.data.id}`).on('click', function CountDown(event) {
        event.preventDefault();
        $.toptip('请稍候')
      })
      // 处理页面样式
      timer = changeCountDownNum(evt.data.id, 60, changeCountDownNum, '获取验证码')
      debugger
      $.ajax(smsURL, {
        method: 'post',
        data: {mobile: phoneValue, send_code: send_code}
      }).done((data) => {
        //array(
        // code:短信通知返回码
        // msg:短信验证码信息
        // id:存储验证码id
        // send_code:验证码
        //)
        if (String(data.send_code) !== `${send_code}` || String(data.code) !== '2') {
          // 重置状态
          clearTimeout(timer)
          $(`#${evt.data.id}`).text('获取验证码')
          $('#getCode').off('click')
          $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
          throw new Error(`请求发生错误, 服务器返回: 3${data.msg}`)
        } else {
          sessionStorage.clear()
          sessionStorage.setItem(`yanzheng_code`, `${data.send_code}`)
        }
      }).fail((err) => {
        console.dir(err)
        // 重置状态
        clearTimeout(timer)
        $(`#${evt.data.id}`).text('获取验证码')
        $('#getCode').off('click')
        $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
        throw new Error(`请求发生错误`)
      })
    }
  </script>
  <!-- 推荐码相关 -->
  <script>
    $(document).ready(() => {
      const ajaxURL = `{:U('Wchat/ajax_ck_fuser')}`
      $(`#invent_code`).on(`keyup`, (evt) => {
        const code = Number($('#invent_code').val()) - 5000
        // 限定10亿人
        if (code < 0 || code > 10e8) {
          $.toptip(`推荐码无效`, 'error')
          evt.preventDefault()
          throw new Error(`推荐码无效`)
          $('#invent_code').removeClass('checkDone')
        }
        const ajaxData = {
          p_id: code
        }
        $.ajax(ajaxURL, {
          method: 'post',
          data: ajaxData
        }).fail((err) => {
          $.toptip(`无法验证推荐码是否正确！请检查网络`, 'error')
          $('#invent_code').removeClass('checkDone')
          evt.preventDefault()
          throw err
        }).done((res) => {
          if (String(res.code) === '1') {
            $.toptip(`推荐码有效`, 'success')
            $('#invent_code').addClass('checkDone')
          } else {
            $.toptip(`推荐码无效`, 'error')
            $('#invent_code').removeClass('checkDone')
          }
        })
      })
    })
  </script>
</body>
</html>